package gdut.jmxywz.action;

import gdut.jmxywz.been.Major;
import gdut.jmxywz.been.Stclass;
import gdut.jmxywz.been.Student;
import gdut.jmxywz.util.PageModel;
import gdut.jmxywz.util.ThreeDES;

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class StudentAction extends BaseAction {

	public static final String STUDENT_SESSION_KEY = "studentSessionKey";
	
	private Major major;
	
    private Stclass stclass;
	
	private Student student;
	
	private List majorList;
	
	private List stclassList;
	
	private ThreeDES threeDES;
	
	private int studentId;
	
	private String password;
	
	private String password2;
	
	private String password3;
	
	private String message="";
	
	private int personalTag=0;

/*----------------分页----------------------*/
	private PageModel pageModel;
	
	private int currentPage=1;
	
	private int pageSize=5;
	
/*----------------检索----------------------*/
	private String searchSelect="";
	
	private String like="like";
	
	private String searchValue="";
	
	private String excelParameter="";
	
/*----------------Excel导入导出----------------------*/
	private File excelFile;
	
	private boolean checkbox;
	
	private boolean checkbox2;
	
/*----------------判断工号是否重复----------------------*/	
	private String studentNum;	
/***********************geter和setter方法*****************************/	
	public Major getMajor() {
		return major;
	}

	public void setMajor(Major major) {
		this.major = major;
	}

	public Stclass getStclass() {
		return stclass;
	}

	public void setStclass(Stclass stclass) {
		this.stclass = stclass;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	public List getMajorList() {
		return majorList;
	}

	public void setMajorList(List majorList) {
		this.majorList = majorList;
	}

	public List getStclassList() {
		return stclassList;
	}

	public void setStclassList(List stclassList) {
		this.stclassList = stclassList;
	}
	
	public PageModel getPageModel() {
		return pageModel;
	}

	public void setPageModel(PageModel pageModel) {
		this.pageModel = pageModel;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public ThreeDES getThreeDES() {
		return threeDES;
	}

	public void setThreeDES(ThreeDES threeDES) {
		this.threeDES = threeDES;
	}
	
	public String getSearchSelect() {
		return searchSelect;
	}

	public void setSearchSelect(String searchSelect) {
		this.searchSelect = searchSelect;
	}

	public String getLike() {
		return like;
	}

	public void setLike(String like) {
		this.like = like;
	}

	public String getSearchValue() {
		return searchValue;
	}

	public void setSearchValue(String searchValue)throws UnsupportedEncodingException {
		this.searchValue = new String(searchValue.getBytes("ISO-8859-1"),"utf-8");
	}

	public String getExcelParameter() {
		return excelParameter;
	}

	public void setExcelParameter(String excelParameter) {
		this.excelParameter = excelParameter;
	}
	
	public int getStudentId() {
		return studentId;
	}

	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getPassword3() {
		return password3;
	}

	public void setPassword3(String password3) {
		this.password3 = password3;
	}
	
	public File getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(File excelFile) {
		this.excelFile = excelFile;
	}

	public boolean isCheckbox() {
		return checkbox;
	}

	public void setCheckbox(boolean checkbox) {
		this.checkbox = checkbox;
	}
	
	public boolean isCheckbox2() {
		return checkbox2;
	}

	public void setCheckbox2(boolean checkbox2) {
		this.checkbox2 = checkbox2;
	}
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public int getPersonalTag() {
		return personalTag;
	}

	public void setPersonalTag(int personalTag) {
		this.personalTag = personalTag;
	}
	
	public String getStudentNum() {
		return studentNum;
	}

	public void setStudentNum(String studentNum) {
		this.studentNum = studentNum;
	}

	/*################################################################################*/
	public String PreAdd() throws Exception {
		// TODO Auto-generated method stub
		String hql="from Stclass s order by s.major asc,s.stclassId";
		stclassList=this.getCommonService().findListByHql(hql, null);
		
		return "preAdd";
	}

	
	public String Add() throws Exception {
		// TODO Auto-generated method stub
		if(student.getStclass()==null)return "returnStclassAdd";
		threeDES.getKey(threeDES.getStudentKey());
		student.setStudentPwd(threeDES.getEncString(student.getStudentPwd()));
		boolean bl=this.getCommonService().saveObject(student);
		if(!bl){
			return "error";
		}
		return "add";
	}

	
	public String Show() throws Exception {
		// TODO Auto-generated method stub
		String hql="from Student";
		pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize, "studentShow.action", "");
		return "show";
		
	}

	
	public String Search() throws Exception {
		// TODO Auto-generated method stub
		String hql="from Student";
		String searchParameter="";
		
		String searchValue1=searchValue;
		
		if (like.equals("like")) {
			hql = hql + " as bf  where bf." + searchSelect + " like '%"+ searchValue1 + "%'";
		} else {
			hql = hql + " as bf  where bf." + searchSelect + " ='"+ searchValue1 + "'";
		}
		
		String enSearchValue=java.net.URLEncoder.encode(searchValue1,"UTF-8");//URL编码转换
		excelParameter="?searchSelect="+searchSelect+"&searchValue="+enSearchValue+"&like="+like;
		
		searchParameter="&searchSelect="+searchSelect+"&searchValue="+enSearchValue+"&like="+like;
		
		pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize,"studentSearch.action",searchParameter);

		return "search";
		
	}

	
	public String Detail() throws Exception {
		// TODO Auto-generated method stub
		student=(Student)this.getCommonService().findByIntId(studentId, "gdut.jmxywz.been.Student");
		if(student==null){
			return "error";
		}
		
		return "detail";
	}

	
	public String PreUpdate() throws Exception {
		// TODO Auto-generated method stub
		String hql="from Stclass s order by s.major asc,s.stclassId";
		stclassList=this.getCommonService().findListByHql(hql, null);
		
		student=(Student)this.getCommonService().findByIntId(studentId, "gdut.jmxywz.been.Student");
		if(student==null){
			
			return "error";
		}
		threeDES.getKey(threeDES.getStudentKey());
		student.setStudentPwd(threeDES.getDesString(student.getStudentPwd()));
		return "preUpdate";
	}

	
	public String Update() throws Exception {
		// TODO Auto-generated method stub
		
		/*修改密码时先判断旧密码是否错误，如果错误就不给修改*/
		//System.out.println("-------------------旧密码------------------------"+this.getPassword());
		message="";
		if(this.getPassword()!=null&&!this.getPassword().trim().equals("")){
			Student s=new Student();
			s=(Student)this.getCommonService().findByIntId(student.getStudentId(), "gdut.jmxywz.been.Student");
			threeDES.getKey(threeDES.getStudentKey());
			s.setStudentPwd(threeDES.getDesString(s.getStudentPwd())); 
			if(!this.getPassword().equals(s.getStudentPwd())){
				message="旧密码输入错误！请重新输入...";
				String hql="from Stclass s order by s.major asc,s.stclassId";
				stclassList=this.getCommonService().findListByHql(hql, null);
				
				student=(Student)this.getCommonService().findByIntId(student.getStudentId(), "gdut.jmxywz.been.Student");
				if(student==null){
					
					return "error";
				}
				threeDES.getKey(threeDES.getStudentKey());
				student.setStudentPwd(threeDES.getDesString(student.getStudentPwd()));
				return "preUpdate";
			}
			if(this.getPassword2()!=null&&!this.getPassword2().trim().equals("")){ 
				student.setStudentPwd(password2);
			}
		}
	
		threeDES.getKey(threeDES.getStudentKey());
		student.setStudentPwd(threeDES.getEncString(student.getStudentPwd()));
		
		boolean bl=this.getCommonService().updateObject(student);
		if(!bl){
			return "error";
		}
		if(personalTag==1)
			return "personalSuccess";
		return "update";
	}

	
	public String Delete() throws Exception {
		// TODO Auto-generated method stub
		student=(Student)this.getCommonService().findByIntId(studentId, "gdut.jmxywz.been.Student");
		if(student==null){
			return "error";
		}
		
		boolean bl=this.getCommonService().deleteObject(student);
		if(!bl){
			return "error";
		}
		return "delete";
	}

	
	public String ImportExcel() throws Exception {
		// TODO Auto-generated method stub
		int count=0;
		try{
		FileInputStream fis=new FileInputStream(excelFile);
		jxl.Workbook jwb=Workbook.getWorkbook(fis);
		int sheets=jwb.getNumberOfSheets();
		for(int i=0;i<sheets;i++){
			Sheet rs=jwb.getSheet(i);
			int columnNum=rs.getColumns();
			int rowNum=rs.getRows();
			if(rowNum>0&&columnNum!=4){
				System.out.println("--------------------导入格式不对----------------------");
				return "error";
			}
			Cell cell;
			Cell cellMajor;
			Cell cellStclass;
			for(int row=1;row<rowNum;row++){
				cell=rs.getCell(0, row);
				cellMajor=rs.getCell(2, row);
				cellStclass=rs.getCell(3, row);
				String hql="from Student stu where stu.studentNum='"+cell.getContents()
							+"' and stu.stclass.major.majorName='"+cellMajor.getContents()
							+"' and stu.stclass.stclassName='"+cellStclass.getContents()+"'";
				List l=this.getCommonService().findListByHql(hql, null);
				
				if(l.size()==0){
					student=new Student();
					student.setStudentNum(cell.getContents());
					/*增加不存在的学生时，密码默认为学号*/
					threeDES.getKey(threeDES.getStudentKey());
					student.setStudentPwd(threeDES.getEncString(cell.getContents())); 
				}else{
					student=(Student)l.get(0);
				}
				
				cell=rs.getCell(1, row);
				student.setStudentName(cell.getContents());
				
				cell=rs.getCell(2, row);
				String findMajorId="from Major m where m.majorName='"+cell.getContents()+"'";
				List lm=this.getCommonService().findListByHql(findMajorId, null);
				
				if(lm.size()==0){
					if(checkbox){
						/*新增专业*/
						major=new Major();
						major.setMajorName(cell.getContents());
						boolean addMajorBl=this.getCommonService().saveObject(major);
						if(!addMajorBl){
							System.out.println("-----------------新增专业出错-----------------");
							return "error";
						}
						String findAddMajorId="from Major m where m.majorName='"+cell.getContents()+"'";
						List lam=this.getCommonService().findListByHql(findAddMajorId, null);
						major=(Major)lam.get(0);
						/*新增班级*/
						stclass=new Stclass();
						stclass.setMajor(major);
						cell=rs.getCell(3,row);
						stclass.setStclassName(cell.getContents());
						boolean addStclassBl=this.getCommonService().saveObject(stclass);
						if(!addStclassBl){
							System.out.println("-----------------新增班级出错1-----------------");
							return "error";
						}
						String findAddStclassId="from Stclass stc where stc.stclassName='"+cell.getContents()+"'";
						List las=this.getCommonService().findListByHql(findAddStclassId, null);
						stclass=(Stclass)las.get(0);
					}else{
						continue;
					}
				}else{
					/*专业存在，班级不存在*/
					cell=rs.getCell(3, row);
					Major majorFind=(Major)lm.get(0);
					String findStclassId="from Stclass stc where stc.stclassName='"+cell.getContents()+"' and stc.major.majorId='"+majorFind.getMajorId()+"'";
					List ls=this.getCommonService().findListByHql(findStclassId, null);
					if(ls.size()!=0){
						System.out.println("-----------------------对应班级、专业存在-------------------------");
					}
					if(ls.size()==0){
						if(checkbox2){
							/*新增班级*/
							major=(Major)lm.get(0);
							stclass=new Stclass();
							stclass.setMajor(major);
							cell=rs.getCell(3,row);
							stclass.setStclassName(cell.getContents());
							boolean addStclassBl=this.getCommonService().saveObject(stclass);
							if(!addStclassBl){
								System.out.println("-----------------新增班级出错2-----------------");
								return "error";
							}
							String findAddStclassId="from Stclass stc where stc.stclassName='"+cell.getContents()+"'";
							List las2=this.getCommonService().findListByHql(findAddStclassId, null);
							stclass=(Stclass)las2.get(0);
						}else{
							continue;
						}
					}else{
						stclass=(Stclass)ls.get(0);
					}
				}
		
				student.setStclass(stclass);
				
				boolean bl;
				if(l.size()==0){
					bl=this.getCommonService().saveObject(student);
					count++;
				}else{
					bl=this.getCommonService().updateObject(student);
					count++;
				}
				if(!bl){
					System.out.println("------------------存入数据库出错-------------------");
				}
				
			}
		}
		System.out.println("=================一共导入数据数：================="+count);
		jwb.close();
		fis.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "importExcel";
	}
	
	public void ExportExcel() throws Exception {
		// TODO Auto-generated method stub
		try{
			String[] str=new String[]{"学号","姓名","专业","班级"};
			List list;
			
			if(!searchSelect.equals("")){
				String hql="from Student";
				System.out.println("++++++++++++++++++++++++++++"+searchSelect+like+searchValue);
				String searchValue1=searchValue;
				
				if (like.equals("like")) {
					hql = hql + " as bf  where bf." + searchSelect + " like '%"+ searchValue1 + "%'";
				} else {
					hql = hql + " as bf  where bf." + searchSelect + " ='"+ searchValue1 + "'";
				}
				
				list=this.getCommonService().findListByHql(hql, null);
			}else{
				String hql="from Student";
				list=this.getCommonService().findListByHql(hql, null);
			
			}
			if(list==null)
				return;
			HttpServletResponse response=ServletActionContext.getResponse();
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			response.setContentType("APPLICATION/OCTET-STREAM ");
			response.setHeader("Content-Disposition","attachment; filename="+java.net.URLEncoder.encode("学生.xls","UTF-8"));
			WritableWorkbook wwb=Workbook.createWorkbook(response.getOutputStream());
			WritableSheet sheet=wwb.createSheet("sheet1", 0);
			sheet.setColumnView(0, 20);
			sheet.setColumnView(1, 20);
			sheet.setColumnView(2, 20);
			sheet.setColumnView(3, 20);
			
			Label label=null;
			for(int i=0;i<str.length;i++){
				label=new Label(i,0,str[i]);
				sheet.addCell(label);
			}
			for(int i=0;i<list.size();i++){
				student=(Student)list.get(i);
				
				label=new Label(0,i+1,student.getStudentNum());
				sheet.addCell(label);
				label=new Label(1,i+1,student.getStudentName());
				sheet.addCell(label);
				label=new Label(2,i+1,student.getStclass().getMajor().getMajorName());
				sheet.addCell(label);
				label=new Label(3,i+1,student.getStclass().getStclassName());
				sheet.addCell(label);
		
			}
			wwb.write();
			wwb.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return;
	}

	
	public String personalDetail() throws Exception {
		// TODO Auto-generated method stub
		student=(Student)(ActionContext.getContext().getSession().get("studentSessionKey"));
		if(student==null)
			return "input";
		studentId=student.getStudentId();
		return SUCCESS;
	}
	
	public String personalPreUpdate() throws Exception {
		// TODO Auto-generated method stub
		student=(Student)(ActionContext.getContext().getSession().get("studentSessionKey"));
		if(student==null)
			return "input";
		studentId=student.getStudentId();
		personalTag=1;
		return SUCCESS;
	}
	
	/**
	 * 异步实现校验新增学号是否存在
	 * @throws Exception
	 */
	public void validateNum() throws Exception {
		// TODO Auto-generated method stub
		 HttpServletResponse res = ServletActionContext.getResponse();
		 res.setCharacterEncoding("utf-8");
		 res.setContentType("text/xml");
		 PrintWriter out = null;
		 if(studentNum!=null){
			 String hql="select stu from Student stu where stu.studentNum='"+studentNum+"'";
			 List studentCheckList=this.getCommonService().findListByHql(hql, null);
			 /*如果新增工号在数据库中存在，则返回字符串true，作为js文件处理标记*/
			 if(studentCheckList.size()>0){
				 try {   
			            out = res.getWriter();   
			            out.print("<root>");   
			            out.print("<message>");   
			            out.print("true");   
			            out.print("</message>");   
			            out.print("</root>");   
			        } catch (Exception e) {   
			            e.printStackTrace();   
			        } finally {   
			            out.flush();   
			            out.close();   
			        }   
			 }
		 }		 
	}
	
}
